package io.emqx.cloud;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.MqttPersistenceException;
import org.eclipse.paho.client.mqttv3.MqttTopic;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

public class Server {

    public static final String HOST = "ws://121.40.91.87:8083";
    public static final String TOPIC = "ZUCC-HJX";
  
    private static final String clientid = "hjx_java_mqtt";

    private MqttClient client;
    private MqttTopic topic;
    private MqttTopic topic125;
    private String userName = "hjx";
    private String passWord = "123456";

    private MqttMessage message;

    public Server() throws MqttException {
       
        client = new MqttClient(HOST, clientid, new MemoryPersistence());
        connect();
    }

    private void connect() {
        MqttConnectOptions options = new MqttConnectOptions();
        options.setCleanSession(false);
        options.setUserName(userName);
        options.setPassword(passWord.toCharArray());
        
        options.setConnectionTimeout(10);
       
        options.setKeepAliveInterval(20);
        try {
            client.setCallback(new Callback());
            client.connect(options);
            topic = client.getTopic(TOPIC);
           
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void publish(MqttTopic topic , MqttMessage message) throws MqttPersistenceException,
            MqttException {
        MqttDeliveryToken token = topic.publish(message);
        token.waitForCompletion();
        System.out.println("message is published completely! "
                + token.isComplete());
    }

    public static void main(String[] args) throws MqttException {
        Server server = new Server();

        server.message = new MqttMessage();
        server.message.setQos(2);
        server.message.setRetained(true);
        server.message.setPayload("缁欏鎴风124鎺ㄩ�佺殑淇℃伅".getBytes());
        server.publish(server.topic , server.message);
        server.message = new MqttMessage();
        server.message.setQos(2);
        server.message.setRetained(true);
        server.message.setPayload("缁欏鎴风125鎺ㄩ�佺殑淇℃伅".getBytes());
        server.publish(server.topic125 , server.message);

        System.out.println(server.message.isRetained() + "------ratained鐘舵��");
    }
}
